package org.u2ml.stack.web.rest;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;

import org.restlet.ext.jaxrs.internal.provider.AbstractProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.u2ml.stack.xml.XmlStreamer;

@Component
@Provider
@Produces( { "application/xml", MediaType.TEXT_XML, "application/*+xml" })
@Consumes( { "application/xml", MediaType.TEXT_XML, "application/*+xml" })
public class RestXmlProvider extends AbstractProvider<Object> {
	private final Logger logger = LoggerFactory.getLogger(RestXmlProvider.class);
	
	@Autowired
	private XmlStreamer xmlStreamer;

	@Override
    public boolean isReadable(Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        boolean streamable = xmlStreamer.isStreamable(type);
        if (!streamable) {
        	logger.warn("requested to stream {} from XML but it has no XStreamAlias and is not an Entity: not readable", type);
        }
		return streamable;
    }

    @Override
    public boolean isWriteable(Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return xmlStreamer.isStreamable(type);
    }

	@Override
	public long getSize(Object object, Class<?> type, Type genericType,
			Annotation[] annotations, MediaType mediaType) {
		return -1;
	}

	@Override
	public Object readFrom(Class<Object> type, Type genericType,
			Annotation[] annotations, MediaType mediaType,
			MultivaluedMap<String, String> httpResponseHeaders,
			InputStream entityStream) throws IOException {
		return xmlStreamer.fromXML(entityStream, type);
	}

	@Override
	public void writeTo(Object object, Class<?> type, Type genericType,
			Annotation[] annotations, MediaType mediaType,
			MultivaluedMap<String, Object> httpHeaders,
			OutputStream entityStream) throws IOException {
		xmlStreamer.toXML(object, entityStream);
	}
}
